package net.yebaihe.wc;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;

import net.yebaihe.wc.DataMan.MSGTYPE;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class UserInfo extends StateMachine{

	TextView txtEmail,txtUsername;
	ImageView img;
	private File tempFile=new File("/sdcard/aaaaaaaaaaaaa.jpg");

	@Override
	protected String getTopbarTitle() {
		return "个人资料";
	}

	@Override
	protected void prepareClient(View client) {
		txtEmail=(TextView) client.findViewById(R.id.txtEmail);
		txtUsername=(TextView) client.findViewById(R.id.txtUsername);
		img=(ImageView)client.findViewById(R.id.imgImage);
		UserInfoData data=MyHelper.get(this).getCurrUserInfoData(this.getWCAppContext().email);
		txtEmail.setText("邮箱："+data.email);
		txtUsername.setText("用户名："+data.username);
		
		Button btnLibrary=(Button) this.findViewById(R.id.btnLibrary);
		btnLibrary.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);  
		        intent.setType("image/*");  
		        intent.putExtra("crop", "true");  
		        intent.putExtra("aspectX", 2);  
		        intent.putExtra("aspectY", 2);  
		        intent.putExtra("output", Uri.fromFile(tempFile));
                intent.putExtra("outputFormat", "JPEG");
		        startActivityForResult(Intent.createChooser(intent, "选择图片"), 1);  
			}
		});		
		
		if (data.image!=null){
			img.setImageBitmap(data.image);
		}
	}

	protected void onActivityResult(int requestCode, int resultCode,  
			Intent data){  
		switch (resultCode){  
		case RESULT_OK:
			Bitmap bmp=BitmapFactory.decodeFile(tempFile.getAbsolutePath());
			DataMan.get(this).updateCurrUserImageInfo(bmp);
			img.setImageBitmap(bmp);			
			tempFile.delete();
			break;
		}  
	}  
	
	@Override
	protected void HandleMessage(MSGTYPE msgtype, boolean ret,
			HashMap<String, String> params) {
		switch (msgtype){
		case UPDATE_IMAGE:
			if (ret){
				Toast.makeText(this, "更新用户头像成功！", Toast.LENGTH_LONG).show();
				UserInfoData data=MyHelper.get(this).getCurrUserInfoData(this.getWCAppContext().email);
				img.setImageBitmap(data.image);
			}
			break;
		}
	}

	@Override
	protected int getLayoutRes() {
		return R.layout.userinfo;
	}

}
